<template>
  <div>
    <!-- Breadcrumb 面包屑 导航区-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">权限管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- Card 卡片 卡片视图区-->
    <el-card class="box-card">
      <!-- 添加角色按钮区-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区-->
      <el-table :data="roleList" border stripe>
        <!--展开列 type="expand"-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 通过FOR 循环嵌套 渲染一级权限-->
            <el-row
              :class="['bdbottom', 'vcenter', i1 === 0 ? 'bdtop' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 左侧列-->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="remvoeRightByID(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二、三级权限 右侧列-->
              <el-col :span="19">
                <!-- 通过FOR 循环嵌套 渲染二级权限-->
                <el-row
                  :class="['vcenter', i2 === 0 ? '' : 'bdtop']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 左侧列-->
                  <el-col :span="5">
                    <el-tag
                      closable
                      type="warning"
                      @close="remvoeRightByID(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 右侧列-->
                  <el-col :span="10">
                    <!-- 通过FOR 循环嵌套 渲染三级权限-->
                    <el-row v-for="item3 in item2.children" :key="item3.id">
                      <el-col>
                        <el-tag
                          closable
                          @close="remvoeRightByID(scope.row, item3.id)"
                          type="danger"
                          >{{ item3.authName }}</el-tag
                        >
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!--<pre> {{ scope.row }}</pre>-->
          </template>
        </el-table-column>
        <!-- 索引列 type="index"-->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加用户对话框-->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 对话框内容主体区 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="90px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--  对话框底部区-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框-->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 修改对话框内容主体区 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo()">确 定</el-button>
      </span>
    </el-dialog>
    <!--分配权限对话框-->
    <el-dialog
      title="分配权限"
      :visible.sync="SetRightDialogVisible"
      width="50%"
      @close="SetRightDialogClosed"
    >
      <!--  树形控件区-->
      <!-- node-key每个树节点用来作为唯一标识的属性，整棵树应该是唯一的-->
      <el-tree
        :data="rightList"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defaultCheckedKkeys"
        :props="treeProps"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 所有角色列表
      roleList: null,
      rightList: null, // 所有权限树
      treeProps: {
        // 树形控件的属性绑定
        children: 'children',
        label: 'authName'
      },
      defaultCheckedKkeys: [], // 默认选中的节点数组
      addDialogVisible: false, // 添加角色对话框显示与隐藏
      editDialogVisible: false, // 修改角色对话框显示与隐藏
      SetRightDialogVisible: false, // 分配权限对话框显示与隐藏
      RoleID: null,
      // 添加表单数据
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 查询到的信息数据
      editForm: {
        roleName: '',
        id: '',
        roleDesc: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '角色名称长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '角色描述长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ]
      },
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '角色名称长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '角色描述长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 优化异步操作 async await
    async getRolelist () {
      const { data: res } = await this.$http.get('roles/')
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.roleList = res.data
    },
    // 添加用户对话框关闭 事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 修改用户对话框关闭 事件处理函数
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击确定按钮 添加角色表单处理
    addRole () {
      this.$refs.addFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) {
          return false
        } // 验证失败
        // 发起添加用户表单的网络请求
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功！')
        this.addDialogVisible = false
        this.getRolelist()
      })
    },
    // 修改角色信息并提交
    editRoleInfo () {
      this.$refs.editFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) {
          return false
        } // 验证失败
        // 发起添加用户表单的网络请求
        // let fomrdata = {
        //   email: this.editForm.email,
        //  mobile: this.editForm.mobile
        // }
        console.log(this.editForm)
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          this.editForm
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色失败')
        }
        this.$message.success('修改角色成功！')
        this.editDialogVisible = false
        this.getRolelist()
      })
    },
    // 显示修改对话框 事件处理函数
    async showEditDialog (id) {
      console.log(id)
      const { data: res } = await this.$http.get('roles/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('读取用户信息失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 删除角色信息 根据ID
    async deleteRole (id) {
      console.log(id)
      const confirmres = await this.$confirm(
        '此操作将永久删除编号为' + id + '的角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => {
        return err // 通过异常捕获，如果用户点击取消，则返回字符串‘cancel’
      })
      // 如果用户确认删除，则返回字符串‘confirm’
      console.log(confirmres)
      if (confirmres !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色信息失败')
      }
      this.$message.success('删除角色信息成功！')
      this.getRolelist()
    },
    // 根据ID删除权限
    async remvoeRightByID (role, rightId) {
      let roleId = role.id
      console.log(role.id)
      console.log(rightId)
      const confirmres = await this.$confirm(
        '此操作将永久删除编号为' +
          roleId +
          '的角色下的' +
          rightId +
          '权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => {
        return err // 通过异常捕获，如果用户点击取消，则返回字符串‘cancel’
      })
      // 如果用户确认删除，则返回字符串‘confirm’
      console.log(confirmres)
      if (confirmres !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        'roles/' + roleId + '/rights/' + rightId
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色的权限信息失败')
      }
      this.$message.success('删除角色的权限信息成功！')
      role.children = res.data
      // this.getRolelist()
    },
    // 显示分配权限对话框
    async showSetRightDialog (role) {
      // 获取所有权限的数据列表
      this.RoleID = role.id
      const { data: res } = await this.$http.get('rights/tree')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rightList = res.data // 把获取到的权限数据保存到data中
      console.log(this.rightList)
      // 递归获得三级节点
      this.getDefKeys(role, this.defaultCheckedKkeys)
      this.SetRightDialogVisible = true
    },
    // 通过递归的形式，获取角色下所有的三级权限的id，并保存到defaultCheckedKkeys数组中
    getDefKeys (node, array) {
      // 如果当前node节点不含children属性，则是三级节点
      if (!node.children) {
        return array.push(node.id)
      }
      node.children.forEach(element => {
        this.getDefKeys(element, array)
      })
    },
    // 分配权限对话框关闭
    SetRightDialogClosed () {
      this.defaultCheckedKkeys = []
    },
    // 提交分配权限
    async allotRights () {
      let HalfCheckedKeys = this.$refs.treeRef.getHalfCheckedKeys()
      let CheckedKeys = this.$refs.treeRef.getCheckedKeys()
      let Keys = HalfCheckedKeys.concat(CheckedKeys)
      console.log(Keys)
      // 数组转换为字符串
      const IDstr = Keys.join(',')
      console.log(IDstr)
      const { data: res } = await this.$http.post(
        'roles/' + this.RoleID + '/rights',
        { rids: IDstr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新权限列表失败')
      }
      this.$message.success('更新权限列表成功！')
      this.getRolelist()
      this.SetRightDialogVisible = false
    }
  },
  created () {
    this.getRolelist()
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  /* 纵向居中*/
  display: flex;
  align-items: center;
}
</style>
